package io.kiki.sba.registry.server.metadata.slot.manager;

import io.kiki.sba.registry.common.model.slot.Slots;
import io.kiki.sba.registry.exception.InitializeException;
import io.kiki.sba.registry.lifecycle.impl.LifecycleHelper;
import io.kiki.sba.registry.server.metadata.MetadataLeaderService;
import io.kiki.sba.registry.server.metadata.remoting.notifier.Notifier;
import io.kiki.sba.registry.server.metadata.slot.SlotManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;


@Component
public class DefaultSlotManagerImpl extends SlotManagerImpl implements SlotManager {
    private static final Logger logger = LoggerFactory.getLogger(SlotManagerImpl.class);
    @Autowired(required = false)
    List<Notifier> notifierList;

    @Autowired
    private MetadataLeaderService metadataLeaderService;

    public DefaultSlotManagerImpl() {
    }

    public DefaultSlotManagerImpl(MetadataLeaderService metadataLeaderService) {
        this.metadataLeaderService = metadataLeaderService;
    }

    @PostConstruct
    public void postConstruct() throws Exception {
        LifecycleHelper.initializeIfPossible(this);
    }

    @Override
    protected void doInitialize() throws InitializeException {
        super.doInitialize();
        addObserver(new SlotsChangeNotification(this));
    }

    @Override
    public boolean refresh(Slots slots) {
        // if we are not leader, could not refresh table
        // this maybe happens in fgc:
        // before arrange we are leader, but calc takes too much time
        if (!metadataLeaderService.amILeader()) {
            throw new IllegalStateException("not leader, concurrent leader is:" + metadataLeaderService.getLeader());
        }
        if (super.refresh(slots)) {
            notifyObservers(slots);
            return true;
        }
        return false;
    }


}
